<?php


namespace app\home\controller;


use app\base\BaseController;
use app\home\model\InReceiptDetail;
use app\home\severs\OutReceiptSever;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\App;
use think\Exception;
use think\facade\Db;
use think\facade\View;

/**
 * Class OutReceipt
 * @package app\home\controller
 * 出库单
 */
class OutReceipt extends BaseController
{
    protected $table='out_receipt';
    protected $title='出库单';
    private $sessionKey='pageOutReceipt';
    protected $businessType=[
//        '销售发货',
//        '采购退货',
//        '生产领料',
//        '委外发货',
//        '委外退货',
//        '其他出库',
//        '调拨出库',
//        '盘亏出库'
    ];//业务类型
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->businessType=config('config.outReceiptType');
    }
    /**
     * date:2024/3/21
     * 列表
     */
    public function index()
    {
        $param=$this->param;
        if (request()->isAjax()) {
            $where[]=['i.status','>',-1];
            foreach (['i_type','i_id','i_status'] as $i){
                if (isset($param[$i])&&$param[$i]){
                    $k=str_replace('_','.',$i);
                    $where[]=[$k,'=',$param[$i]];
                }
            }
            foreach (['p_name','u_name','i_orderNum'] as $i){
                if (isset($param[$i])&&$param[$i]){
                    $k=str_replace('_','.',$i);
                    $where[]=[$k,'like','%'.$param[$i].'%'];
                }
            }
            if (isset($param['i_outTime'])&&$param['i_outTime']){
                $times=explode('~',$param['i_outTime']);
                $where[]=['i.outTime','between',$times];
            }
            session($this->sessionKey,$where);
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name($this->table)->alias('i')
                ->join('purveyor p','p.id=i.punter_id','left')
                ->join('admin u','u.id=i.out_user','left')
                ->where($where)
                ->field('i.*,p.name as pName,u.name as username')
                ->order('i.id DESC')
                ->paginate($rows);
            return table_assign(0, '', $list);
        } else {
            View::assign('typeList',$this->businessType);
            return view();
        }

    }

    /**
     * @return \json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * date:2024/3/21
     * 添加
     */
    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $postData=$this->param;
            $mxid=$postData['mxid']??[];
            $material_id=$postData['material_id']??[];
            $num=$postData['num']??[];
            $oldNum=$postData['oldNum']??[];
            $warehouse_id=$param['warehouse_id']??[];
            $locator=$param['locator']??[];
            $o_remark=$param['o_remark']??[];
            $oCode=$postData['oCode']??'';
//            if ($oldNum){
//                foreach ($oldNum as $k=>$o){
//                    if ($num[$k]>$oldNum[$k]){
//                        return to_assign(1,'数量大于剩余数量');
//                        break;
//                    }
//                }
//            }
            $param=[
                'type'=>$postData['type'],
                'outTime'=>$postData['outTime'],
                'status'=>$postData['status'],
                'oCode' => $postData['oCode'],
                'punter_id'=>$postData['punter_id'],
                'printCompany'=>$postData['printCompany'],
                'id'=>$postData['id']??0,
            ];
            if (!$material_id){
                return to_assign(1,'参数缺失');
            }

            Db::startTrans();
            $param['update_time']=time();
            $id=$param['id']??0;
            try {
                if ($param['id'] > 0) {
//                    $param['orderNum'] = $postData['orderNum']??'';
//                    if (!$param['orderNum']){
//                        throw new Exception( '单据编号不能为空');
//                    }
                    $info=Db::name($this->table)->where('id',$id)->find();
                    $param['orderNum'] = $postData['orderNum']??'';
//                    if ($info['oCode']!=$oCode){
//                        $param['orderNum']=$this->getDJBHBuySql($this->table,'orderNum',$oCode);
//                    }
                    $whereDh[]=['status','>',-1];
                    $whereDh[]=['orderNum','=',$param['orderNum']];
                    if (isset($param['id'])&&$param['id']){
                        $whereDh[]=['id','<>',$param['id']];
                    }
                    if (Db::name($this->table)->where($whereDh)->value('orderNum')){
                       throw new Exception( '单据编号已存在');
                    }
                    Db::name($this->table)->strict(false)->field(true)->update($param);
                    add_log('edit', $param['id'], $postData,$this->title);
                } else {
//                    $w_codeId=$warehouse_id[0]??1;
//                    $wCode=Db::name('warehouse')->where('id',$w_codeId)->value('wCode');
//                    $ordernum=$this->getDJBHBuySql($this->table,'orderNum',$wCode);
                    $ordernum=$this->getDJBHBuySql($this->table,'orderNum',$oCode);
                    $param['orderNum']=$ordernum;
                    $param['create_time'] = time();
                    $param['create_user'] = $this->uid;
                    $id = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                    add_log('add', $id, $postData,$this->title);
                }
                $det_data=$this->createMxData($material_id,$num,$mxid,$warehouse_id,$locator,$o_remark);
                foreach ($det_data as $v){
//                    $materialInfo=Db::name('material_dossier_kucun_view')
//                        ->where('id',$v['mt_id'])->field('countNum,sendNum')->find();
//                    if ($v['num']>($materialInfo['countNum']-$materialInfo['sendNum'])){
//                        throw new Exception('数量大于剩余数量');
//                    }
                    $mxData=[
                        'out_receipt_id'=>$id,
                        'material_dossier_id'=>$v['mt_id'],
                        'num'=>$v['num'],
                        'warehouse_id'=>$v['warehouse_id'],
                        'locator'=>$v['locator'],
                        'o_remark'=>$v['o_remark']??'',
                        'create_time'=>time(),
                        'update_time'=>time()
                    ];
                    if (isset($v['mx_id'])&&$v['mx_id']){
                        $mxData['id']=$v['mx_id'];
                    }
                    Db::name('out_receipt_detail')->save($mxData);
                }
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败:'.$e->getMessage());
            }

            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->field("*,(select name from fy_admin a where a.id=out_user)username")->find();
                View::assign('detail', $detail);
                $mxList=Db::name('out_receipt_detail')
                    ->alias('ord')
                    ->where('ord.status','>','-1')->where('ord.out_receipt_id',$id)
                    ->leftJoin('material_kucun_view mdkv','ord.material_dossier_id=mdkv.mdId and ord.warehouse_id =mdkv.wId')
                    ->field('ord.*,mdkv.mdName,mdkv.bar_code,mdkv.specs,mdkv.mdBrand,mdkv.unit,mdkv.warehouseName,mdkv.locatorName,mdkv.countNum,mdkv.sendNum')
                    ->select()->each(function ($item,$index){
                        $item['haveNum']=$item['countNum']-$item['sendNum']+$item['num'];
                        return $item;
                    });
                View::assign('mxList', $mxList);
            }
            $punterList=Db::name('purveyor')->where('status',1)->field('id,name')->select();
            $printCompany=config('config.companyName');
            $orCode=config('config.oCode');
            View::assign('printCompany', $printCompany);
            View::assign('typeList',$this->businessType);
            View::assign('punterList',$punterList);
            View::assign('id', $id);
            View::assign('orCode', $orCode);
            View::assign('defalutTime', date('Y-m-d'));

            return view('form');
        }
    }

    public function addMx()
    {
        if (request()->isPost()) {
            $where[]=['mdId','>',0];
            foreach (['bar_code','mdName','mdBrand','specs','locatorName','warehouseName'] as $v){
                if (isset($this->param[$v])&&$this->param[$v]){
                    $where[]=[$v,'like','%'.$this->param[$v].'%'];
                }
            }
            $limit=$this->param['limit']??15;
            $list=Db::name('material_kucun_view')
                ->field("*")
                ->where($where)->paginate($limit)->each(function ($item,$key){
                    $item['sendNum']=$item['sendNum']?$item['sendNum']:0;
                    $item['num']=$item['countNum']-$item['sendNum'];
                    return $item;
                });
            View::assign('list',$list);
            return table_assign(0, '', $list);
        } else {
            return \view('mx');
        }

    }
    public function removeMx()
    {
        $id=$this->param['id'];
        try {
            Db::name('out_receipt_detail')->where('id',$id)->update(['status'=>-1,'update_time'=>time(),'deleted'=>time()]);
            add_log('add', $id, $this->param,$this->title);
        }catch (\Exception $e){
            return to_assign(1,'删除失败:'.$e->getMessage());
        }
        return to_assign();
    }

    /**
     * date:2024/4/18
     * 确认
     */
    public function onSure()
    {
//                $ids=$this->param['id']??'';
//        $ids=explode(',',$ids);
//        $data=[];
//        foreach ($ids as $v){
//            $param=[
//                'id'=>$v
//            ];
//            $data[]=$res=OutReceiptSever::doSure($param,2);
//        }
//        return to_assign(1,'ok',$data);
        $res=OutReceiptSever::doSure($this->param,$this->uid);
        return to_assign($res['code'],$res['msg']);
    }
    public function onCancel()
    {
        $id = $this->param['id'] ?? 0;
        if (!$id) {
            return to_assign(1, '参数缺失');
        }
        $status = Db::name($this->table)->where('id','in', $id)->where('status','=',1)->column('status');
       if ($status){
           return to_assign(1, '操作有误');
       }
        Db::startTrans();
        try {
            $fhorderNum=Db::name($this->table)->where('type','销售发货')
                ->where('id','in',$id)
                ->where('status','2')
                ->column('orderNum');
                    $mxStarus = Db::name('sale_hanging_bill')->where('status','>',1)->where('g_orderNum','in',$fhorderNum)->column('status');
                    if (!empty($mxStarus)){
                        throw new Exception('单据已开始对账,无法撤回');
                    }
                    Db::name('sale_hanging_bill')
                        ->where('status','>',-1)
                        ->where('g_orderNum','in',$fhorderNum)
                        ->update(['status'=>-1,'deleted'=>time(),'update_time'=>time()]);
            Db::name($this->table)->where('id', 'in',$id)->update(['out_user' => $this->uid, 'status' => 1, 'update_time' => time(), 'checkTime' => time()]);
            Db::name('out_receipt_detail')->where('status', '2')
                ->where('out_receipt_id','in', $id)->update(['status' => 1, 'update_time' => time()]);
            add_log('back', $id, $this->param, $this->title);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return to_assign(1, '操作失败:' . $e->getMessage());
        }
        return to_assign(0, '操作成功');

    }
    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/3/21
     * 删除
     */
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            $status=Db::name($this->table)->where('id','in',$id)->column('status');
            if (in_array('2',$status)){
                return  to_assign(1, "有已确认数据，不能删除");
            }
            try {
                Db::name($this->table)->where('id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                Db::name('out_receipt_detail')->where('out_receipt_id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                add_log('delete', $id, request()->param(),$this->title);
            }catch (\Exception $e){
                return to_assign(1, "删除失败".$e->getMessage());
            }
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "错误的请求");
        }
    }
    public function printPage()
    {
        $id=$this->param['id']??'';
        $printType=$this->param['printType']??1;
        $info=Db::name($this->table)->where('id',$id)
            ->field("*,(select name from fy_admin a where a.id=create_user) createName")
            ->find();
        $purInfo=Db::name('purveyor')->where('id',$info['punter_id'])->field('name,code')->find();

        if ($printType==1){
            $info['punterName']=$purInfo['code']??'';
        }elseif($printType==2){
            $info['punterName']=$purInfo['name']??'';
        }else{
            $pName=$purInfo['name']??'';
            $pCode=$purInfo['code']??'';
            $info['punterName']=$pName.' '.$pCode;
        }
        $mxList=Db::name('out_receipt_detail')
            ->alias('ord')
            ->where('ord.status','>',-1)->where('ord.out_receipt_id',$id)
            ->join('material_kucun_view mdkv','mdkv.mdId=ord.material_dossier_id and ord.warehouse_id =mdkv.wId')
            ->field('ord.*,mdkv.mdName,mdkv.bar_code,mdkv.specs,mdkv.mdBrand,mdkv.unit,mdkv.warehouseName,mdkv.locatorName,mdkv.countNum,mdkv.sendNum')
            ->order('ord.id ASC')
            ->select();
        $data=[
             'companyName'=>$info['printCompany'],
            'orderType'=>'出库单',
            'type'=>$info['type'],
            'punterName'=>$info['punterName'],
            'orderNum'=>$info['orderNum'],
            'outTime'=>$info['outTime'],
            'printTime'=>date('Y-m-d H:i:s'),
            'makeUser'=>$info['createName'],
            'qz'=>'',
        ];
        $detail=[];
        foreach ($mxList as $k=> $ml){
            $detail[]=[
                'k'=>$k+1,
                'bar_code'=>$ml['bar_code'],
                'name'=>$ml['mdName'],
                'specs'=>$ml['specs'],
                'unit'=>$ml['unit'],
                'wName'=>$ml['warehouseName'],
//                'locaName'=>$ml['locatorName'],
                'num'=>$ml['num'],
                'o_remark' => $ml['o_remark'],
            ];
        }

        $res=[];
        foreach ($detail as $key=>$v){
            $res[$key]=$v;
        }
        $data['detail']=$res;
//        $temp='{"panels":[{"index":0,"paperType":"A4","height":297,"width":210,"paperHeader":43.5,"paperFooter":801,"printElements":[{"options":{"left":213,"top":58.5,"height":9.75,"width":198,"field":"companyName","testData":"重庆丰逸科技有限公司","fontSize":18,"fontWeight":"bold"},"printElementType":{"type":"text"}},{"options":{"left":270,"top":96,"height":9.75,"width":120,"field":"orderType","testData":"出库单","fontSize":18,"fontWeight":"bold"},"printElementType":{"type":"text"}},{"options":{"left":250.5,"top":139.5,"height":9.75,"width":120,"title":"收货单位","field":"punterName","fontSize":12},"printElementType":{"type":"text"}},{"options":{"left":426,"top":139.5,"height":9.75,"width":159,"title":"单据编号","field":"orderNum","fontSize":12,"testData":"CKD100000008"},"printElementType":{"type":"text"}},{"options":{"left":28.5,"top":141,"height":9.75,"width":120,"title":"业务类型","field":"type","fontSize":12},"printElementType":{"type":"text"}},{"options":{"left":28.5,"top":168,"height":9.75,"width":120,"title":"出库日期","field":"outTime","fontSize":12},"printElementType":{"type":"text"}},{"options":{"left":27,"top":201,"height":48,"width":528,"textAlign":"center","tableHeaderFontWeight":"bolder","field":"detail","columns":[[{"title":"序号","field":"k","width":57.39758501302205,"colspan":1,"rowspan":1,"checked":true},{"title":"物料编码","field":"bar_code","width":54.16558961222166,"colspan":1,"rowspan":1,"checked":true},{"title":"物料名称","field":"name","width":104.3215328036726,"colspan":1,"rowspan":1,"checked":true},{"title":"规格型号","field":"specs","width":57.79074667098496,"colspan":1,"rowspan":1,"checked":true},{"title":"单位","field":"unit","width":50.62406879836136,"colspan":1,"rowspan":1,"checked":true},{"title":"仓库","field":"wName","width":63.88574627218932,"colspan":1,"rowspan":1,"checked":true},{"title":"数量","field":"num","width":66.42044159877895,"colspan":1,"rowspan":1,"checked":true}]]},"printElementType":{"title":"表格","type":"tableCustom"}},{"options":{"left":249,"top":271.5,"height":9.75,"width":141,"title":"制单人","field":"makeUser","fontSize":12},"printElementType":{"type":"text"}},{"options":{"left":427.5,"top":271.5,"height":9.75,"width":136.5,"title":"签字","field":"qz","fontSize":12},"printElementType":{"type":"text"}},{"options":{"left":30,"top":273,"height":9.75,"width":189,"title":"打印时间","field":"printTime","fontSize":12,"testData":"2024-04-22 16:23:34"},"printElementType":{"type":"text"}}],"paperNumberLeft":565,"paperNumberTop":819}]}';
//        $temp='{"panels":[{"index":0,"paperType":"A5","height":148,"width":210,"paperHeader":43.5,"paperFooter":419.52755905511816,"printElements":[{"options":{"left":120,"top":19.5,"height":21,"width":355.5,"field":"companyName","testData":"重庆洪湖摩托车配件制造有限公司","fontSize":18,"fontWeight":"bold","textAlign":"center"},"printElementType":{"type":"text"}},{"options":{"left":247.5,"top":46.5,"height":15,"width":120,"field":"orderType","testData":"出库单","fontSize":18,"fontWeight":"bold"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":66,"height":9.75,"width":195,"title":"业务类型","field":"type","fontSize":12},"printElementType":{"type":"text"}},{"options":{"left":388.5,"top":66,"height":9.75,"width":178.5,"title":"单据编号","field":"orderNum","fontSize":12,"testData":"CKD100000008"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":79.5,"height":13.5,"width":352.5,"title":"收货单位","field":"punterName","fontSize":12,"testData":"重庆洪湖摩托车配件制造有限公司","lineHeight":12.75},"printElementType":{"type":"text"}},{"options":{"left":387,"top":82.5,"height":13.5,"width":178.5,"title":"出库日期","field":"outTime","fontSize":12,"lineHeight":12.75},"printElementType":{"type":"text"}},{"options":{"left":25.5,"top":99,"height":46.5,"width":540,"textAlign":"center","tableHeaderFontWeight":"bolder","field":"detail","fontSize":10.5,"columns":[[{"title":"序号","field":"k","width":49.58427016939213,"colspan":1,"rowspan":1,"checked":true,"columnId":"k"},{"title":"物料编码","field":"bar_code","width":66.01802651327142,"colspan":1,"rowspan":1,"checked":true,"columnId":"bar_code"},{"title":"物料名称","field":"name","width":97.02724150226268,"colspan":1,"rowspan":1,"checked":true,"columnId":"name"},{"title":"规格型号","field":"specs","width":220.26778999175144,"colspan":1,"rowspan":1,"checked":true,"columnId":"specs"},{"title":"单位","field":"unit","width":27.744143814881184,"colspan":1,"rowspan":1,"checked":true,"columnId":"unit"},{"title":"仓库","field":"wName","width":33.90389999740843,"colspan":1,"rowspan":1,"checked":true,"columnId":"wName"},{"title":"数量","field":"num","width":45.454628011032696,"colspan":1,"rowspan":1,"checked":true,"columnId":"num"}]]},"printElementType":{"title":"表格","type":"tableCustom"}},{"options":{"left":262.5,"top":151.5,"height":9.75,"width":111,"title":"检验","field":"jy","fontSize":12},"printElementType":{"type":"text"}},{"options":{"left":378,"top":151.5,"height":9.75,"width":70.5,"title":"收货","field":"sh","fontSize":12},"printElementType":{"type":"text"}},{"options":{"left":154.5,"top":151.5,"height":9.75,"width":105,"title":"配套","field":"pt","fontSize":12},"printElementType":{"type":"text"}},{"options":{"left":457.5,"top":151.5,"height":9.75,"width":120,"title":"制单人","fontSize":12,"field":"makeUser"},"printElementType":{"type":"text"}},{"options":{"left":22.5,"top":151.5,"height":9.75,"width":126,"title":"收货单位签字","field":"shdw","fontSize":12,"testData":"重庆洪"},"printElementType":{"type":"text"}}],"paperNumberLeft":565,"paperNumberTop":397,"orient":1}]}';
//        $temp='{"panels":[{"index":0,"height":150,"width":220,"paperHeader":43.5,"paperFooter":425.19685039370086,"printElements":[{"options":{"left":120,"top":19.5,"height":21,"width":355.5,"field":"companyName","testData":"重庆洪湖摩托车配件制造有限公司","fontSize":18,"fontWeight":"bold","textAlign":"center","showInPage":"first"},"printElementType":{"type":"text"}},{"options":{"left":247.5,"top":46.5,"height":15,"width":120,"field":"orderType","testData":"出库单","fontSize":18,"fontWeight":"bold"},"printElementType":{"type":"text"}},{"options":{"left":28.5,"top":66,"height":9.75,"width":352.5,"title":"业务类型","field":"type","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":388.5,"top":66,"height":9.75,"width":216,"title":"单据编号","field":"orderNum","fontSize":12.75,"testData":"CKD100000008","fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":387,"top":81,"height":13.5,"width":216,"title":"出库日期","field":"outTime","fontSize":12.75,"lineHeight":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":28.5,"top":81,"height":13.5,"width":352.5,"title":"收货单位","field":"punterName","fontSize":12.75,"testData":"重庆洪湖摩托车配件制造有限公司","lineHeight":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":28.5,"top":99,"height":46.5,"width":540,"tableHeaderFontWeight":"500","field":"detail","fontSize":10.5,"fontFamily":"Microsoft YaHei","tableBodyRowHeight":19.5,"columns":[[{"title":"序号","field":"k","width":27.821978377688733,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"k"},{"title":"物料编码","field":"bar_code","width":86.18336766762349,"colspan":1,"rowspan":1,"checked":true,"columnId":"bar_code"},{"title":"物料名称","field":"name","width":61.15263457750072,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"name"},{"title":"规格型号","field":"specs","width":196.06141958511512,"vAlign":"middle","colspan":1,"rowspan":1,"checked":true,"columnId":"specs"},{"title":"单位","field":"unit","width":29.75915847681715,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"unit"},{"title":"数量","field":"num","width":52.52094131525479,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"num"},{"title":"备注","field":"o_remark","width":86.50050000000005,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"o_remark"}]]},"printElementType":{"title":"表格","type":"tableCustom"}},{"options":{"left":262.5,"top":151.5,"height":9.75,"width":111,"title":"检验","field":"jy","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":378,"top":151.5,"height":9.75,"width":70.5,"title":"发货","field":"sh","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":156,"top":151.5,"height":9.75,"width":100.5,"title":"配套","field":"pt","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":457.5,"top":151.5,"height":9.75,"width":120,"title":"制单人","fontSize":12.75,"field":"makeUser","fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":28.5,"top":151.5,"height":9.75,"width":126,"title":"收货单位签字","field":"shdw","fontSize":12.75,"testData":"重庆洪","fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":312,"top":373.5,"height":9.75,"width":114,"title":"蓝色客户","fontSize":12.75,"showInPage":"last","fixed":true,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":169.5,"top":373.5,"height":9.75,"width":114,"title":"红色财务","fontSize":12.75,"showInPage":"last","fixed":true,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":453,"top":373.5,"height":9.75,"width":115.5,"title":"黄色库房","fontSize":12.75,"showInPage":"last","fixed":true,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":373.5,"height":10.5,"width":114,"title":"白色留根","fontSize":13.5,"showInPage":"last","fixed":true,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}}],"paperNumberLeft":595.5,"paperNumberTop":354,"paperNumberDisabled":true,"orient":1}]}';
        $temp='{"panels":[{"index":0,"height":150,"width":220,"paperHeader":96,"paperFooter":420,"printElements":[{"options":{"left":120,"top":19.5,"height":21,"width":355.5,"field":"companyName","testData":"重庆洪湖摩托车配件制造有限公司","fontSize":18,"fontWeight":"bold","textAlign":"center"},"printElementType":{"type":"text"}},{"options":{"left":247.5,"top":46.5,"height":15,"width":120,"field":"orderType","testData":"出库单","fontSize":18,"fontWeight":"bold"},"printElementType":{"type":"text"}},{"options":{"left":28.5,"top":66,"height":9.75,"width":352.5,"title":"业务类型","field":"type","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":388.5,"top":66,"height":9.75,"width":216,"title":"单据编号","field":"orderNum","fontSize":12.75,"testData":"CKD100000008","fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":387,"top":81,"height":13.5,"width":216,"title":"出库日期","field":"outTime","fontSize":12.75,"lineHeight":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":28.5,"top":81,"height":13.5,"width":352.5,"title":"收货单位","field":"punterName","fontSize":12.75,"testData":"重庆洪湖摩托车配件制造有限公司","lineHeight":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":99,"height":45,"width":540,"tableHeaderFontWeight":"500","field":"detail","fontSize":10.5,"fontFamily":"Microsoft YaHei","columns":[[{"title":"序号","field":"k","width":27.821978377688733,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"k"},{"title":"物料编码","field":"bar_code","width":86.18336766762349,"colspan":1,"rowspan":1,"checked":true,"columnId":"bar_code"},{"title":"物料名称","field":"name","width":61.15263457750072,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"name"},{"title":"规格型号","field":"specs","width":196.06141958511512,"vAlign":"middle","colspan":1,"rowspan":1,"checked":true,"columnId":"specs"},{"title":"单位","field":"unit","width":29.75915847681715,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"unit"},{"title":"数量","field":"num","width":52.52094131525479,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"num"},{"title":"备注","field":"o_remark","width":86.50050000000005,"align":"center","colspan":1,"rowspan":1,"checked":true,"columnId":"o_remark"}]]},"printElementType":{"title":"表格","type":"tableCustom"}},{"options":{"left":378,"top":148.5,"height":9.75,"width":70.5,"title":"发货","field":"sh","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei","showInPage":"last"},"printElementType":{"type":"text"}},{"options":{"left":262.5,"top":150,"height":9.75,"width":111,"title":"检验","field":"jy","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei","showInPage":"last"},"printElementType":{"type":"text"}},{"options":{"left":156,"top":150,"height":9.75,"width":100.5,"title":"配套","field":"pt","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei","showInPage":"last"},"printElementType":{"type":"text"}},{"options":{"left":457.5,"top":150,"height":9.75,"width":120,"title":"制单人","fontSize":12.75,"field":"makeUser","fontWeight":"500","fontFamily":"Microsoft YaHei","showInPage":"last"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":150,"height":9.75,"width":126,"title":"收货单位签字","field":"shdw","fontSize":12.75,"testData":"重庆洪","fontWeight":"500","fontFamily":"Microsoft YaHei","showInPage":"last"},"printElementType":{"type":"text"}},{"options":{"left":169.5,"top":174,"height":9.75,"width":114,"title":"红色财务","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":312,"top":174,"height":9.75,"width":114,"title":"蓝色客户","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":453,"top":174,"height":9.75,"width":115.5,"title":"黄色库房","fontSize":12.75,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":174,"height":10.5,"width":114,"title":"白色留根","fontSize":13.5,"fontWeight":"500","fontFamily":"Microsoft YaHei"},"printElementType":{"type":"text"}}],"paperNumberLeft":594,"paperNumberTop":394.5,"paperNumberDisabled":true,"fontFamily":"Microsoft YaHei","orient":1}]}';
        View::assign('temp',$temp);
        View::assign('info',json_encode($data,320));
        return \view();
    }
    public function importData()
    {
        Db::startTrans();
        try {
            if (!isset($_FILES['file'])){
                throw new Exception('请选择上传文件');
            }
            //限制上传表格类型
            $fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
            //application/vnd.ms-excel  为xls文件类型
            if ($fileExtendName != 'xlsx') {
                throw new Exception('必须为excel表格，且必须为xlsx格式！');
            }

            if (is_uploaded_file($_FILES['file']['tmp_name'])) {
                // 有Xls和Xlsx格式两种
//            $objReader = \IOFactory::createReader('Xlsx');
                $objReader = IOFactory::createReader('Xlsx');

                $filename = $_FILES['file']['tmp_name'];

                $objPHPExcel = $objReader->setReadDataOnly(true)->load($filename);  //$filename可以是上传的表格，或者是指定的表格

                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
                $lgData=[];
                $types = [];
                $punids = [];
                $mcodes = [];
                $wids = [];
                $nums = [];
                $times = [];
                $orCodes=[];
                for ($j = 2; $j <= $highestRow; $j++) {
                    $type=$objPHPExcel->getActiveSheet()->getCell("A" . $j)->getFormattedValue();
                    $punter_id=(int)$objPHPExcel->getActiveSheet()->getCell("B" . $j)->getFormattedValue();
                    $mater_code=$objPHPExcel->getActiveSheet()->getCell("C" . $j)->getFormattedValue();
                    $ware_house=$objPHPExcel->getActiveSheet()->getCell("D" . $j)->getFormattedValue();
                    $num=(int)$objPHPExcel->getActiveSheet()->getCell("E" . $j)->getFormattedValue();
                    $time=$objPHPExcel->getActiveSheet()->getCell("F" . $j)->getFormattedValue();
                    $orCode=$objPHPExcel->getActiveSheet()->getCell("G" . $j)->getFormattedValue()??'';
                    $types[] = $type;
                    $punids[] = $punter_id;
                    $mcodes[] = $mater_code;
                    $wids[] = $ware_house?$ware_house:1;
                    $nums[] = $num;
                    $times[] = $time;
                    $orCodes[] = $orCode;

//                    if ($punter_id){
//                        $punter_id=Db::name('punter')->where('status',1)->where('id',$punter_id)->value('id');
//                        if (!$punter_id){
//                            $warText="第".($j-1) ."行填写有误";
//                            throw new Exception($warText);
//                        }
//                    }
//                    $ware_house=Db::name('warehouse')->where('id',$ware_house)->where('status',1)->value('id');
//
//                    if (!$ware_house){
//                        $warText="第".($j-1) ."行填写有误";
//                        throw new Exception($warText);
//                    }
//                    $materInfo=Db::name('material_kucun_view')
//                        ->where('wId',$ware_house)
//                        ->where('bar_code',$mater_code)
//                        ->find();
//
//                    if (!$num||!$materInfo){
//                        $warText="第".($j-1) ."行填写有误";
//                        throw new Exception($warText);
//                    }
//                    if ($num>($materInfo['countNum']-$materInfo['sendNum'])){
//                        $warText="第".($j-1) ."行数量大于剩余数量";
//                        throw new Exception($warText);
//                    }
//
//                    $time=str_replace('/','-',$time);
//                    if (!$type){
//                        $warText="第".($j-1) ."行填写有误";
//                        throw new Exception($warText);
//                    }
                    $lgData[]=[
                        "type" =>$type,
                        "outTime" =>$time,
                        "punter_id" =>$punter_id,
                        'num'=>$num,
                        'bar_code'=>$mater_code,
                    ];
//                    $importData= [
//                        "type" =>$type,
//                        "punter_id" =>$punter_id,
//                        "outTime" =>$time,
//                        "deleted" =>0,
//                        'orderNum'=>orderNum('RKD'),
//                        "create_time"=>time(),
//                        'update_time'=>time()
//                    ] ;
//                    $i_id= Db::name($this->table)->insertGetId($importData);
//                    $detail=[
//                        'out_receipt_id'=>$i_id,
//                        'num'=>$num,
//                        'warehouse_id'=>$ware_house,
//                        'locator'=>1,
//                        'material_dossier_id'=>$materInfo['mdId'],
//                        "create_time"=>time(),
//                        'update_time'=>time()
//                    ];
//                    Db::name('out_receipt_detail')->insert($detail);

                }
                $res=$this->createImportData($types, $punids, $mcodes, $wids, $nums, $times,$orCodes);
                if ($res['code']!=200){
                    throw new Exception($res['msg']);
                }
                $data=$res['data'];
                $importData=$data['importData'];
                $mxData=$data['mxData'];
                $i_id= Db::name($this->table)->insertGetId($importData);
                foreach ($mxData as &$m){
                    $m['out_receipt_id']=$i_id;
                }
                Db::name('out_receipt_detail')
                    ->insertAll($mxData);
                if ($lgData){
                    add_log('import', '', $lgData,$this->title);
                }

                Db::commit();
            }
        }catch (Exception $e){
            Db::rollback();
            add_log('import', '', $e->getMessage(),$this->title);
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();

    }

    /**
     * @param $mart_id
     * @param $num
     * @param $mxIds
     * @param $warehouse_id
     * @param $locator
     * @return array
     * date:2024/6/6
     */
    public function createMxData($mart_id,$num,$mxIds,$warehouse_id,$locator,$o_remark=[])
    {
        $data=[];
        $res=[];
        foreach ($mart_id as $k=>$v){
            $remark=$o_remark[$k]??'';
            $wl_ids=($warehouse_id[$k]??1).'_'.($locator[$k]??1).'_'.$remark;
            if (isset($data['id_'.$v.'_'.$mxIds[$k]])){
                $data['id_'.$v.'_'.$mxIds[$k].'_'.$wl_ids]+=$num[$k];
            }else{
                $data['id_'.$v.'_'.$mxIds[$k].'_'.$wl_ids]=$num[$k];
            }
        }
        foreach ($data as $d=>$t){
            $ids=explode('_',$d);
            $res[]=[
                'mt_id'=>$ids[1],
                'num'=>$t,
                'mx_id'=>$ids[2]?$ids[2]:0,
                'warehouse_id'=>$ids[3]??1,
                'locator'=>$ids[4]??1,
                'o_remark'=>$ids[5]??''
            ];
        }
      return $res;
}
    public function createImportData($types, $punids, $mcodes, $wids, $nums, $times,$orCodes)
    {
        $type1 = array_unique($types);
        $punids1 = array_unique($punids);
        $mcodes1 = array_unique($mcodes);
        $times1 = array_unique($times);
        $wids1=array_unique($wids);
        $orCodes1=array_unique($orCodes);
        if (count($type1) != 1 ) {
            return ['code' => 400, 'msg' => '类型填写不一致'];
        }
        if (count($orCodes1) != 1 ) {
            return ['code' => 400, 'msg' => '单号code填写不一致'];
        }
        if (count($wids1) != 1 ) {
            return ['code' => 400, 'msg' => '仓库填写不一致'];
        }
        if ( count($times1) != 1) {
            return ['code' => 400, 'msg' => '日期填写不一致'];
        }
//        if (count($type1) != 1  || count($orCodes1) != 1 || count($wids1) != 1 || count($times1) != 1) {
//            return ['code' => 400, 'msg' => '数据填写不一致1'];
//        }
//        if (count($type1) != 1  || count($wids1) != 1 || count($times1) != 1) {
//            return ['code' => 400, 'msg' => '数据填写不一致1'];
//        }

        if (isset($punids1[0])&&$punids1[0]) {
            $punter_id = Db::name('purveyor')
                ->where('status', 1)
                ->where('id', $punids1[0])
                ->value('id');
            if (!$punter_id) {
                return ['code' => 400, 'msg' => '单位数据填写有误'];
            }
        }



        $time = str_replace('/', '-', $times1[0]);
        if (!$time) {
            return ['code' => 400, 'msg' => '时间填写有误'];
        }
//        $wCode=Db::name('warehouse')->where('id',$wids1[0])->value('wCode');
        $importData = [
            "type" => $type1[0],
            "punter_id" => $punids1[0],
            "outTime" => $times1[0],
            "oCode" => $orCodes1[0],
            "create_user" => $this->uid,
            'orderNum' => $this->getDJBHBuySql($this->table,'orderNum',$orCodes1[0]),
            "deleted" => 0,
            "create_time" => time(),
            'update_time' => time()
        ];
        $mx1 = [];
        foreach ($mcodes as $k => $w) {
            if (!$nums[$k]){
                return ['code' => 400, 'msg' => '数量填写有误'];
                break;
            }

            if (isset($mx1['wid_' . $w])) {
                $mx1['wid_' . $w] += $nums[$k];
            } else {
                $mx1['wid_' . $w] = $nums[$k];
            }
        }
        $mxData = [];
        foreach ($mx1 as $key => $m1) {
            $str = explode('_', $key);
            $wid = $str[1] ?? '';
//            $ware_house = Db::name('warehouse')->where('id', $wid)->where('status', 1)->value('id');
//            if (!$ware_house) {
//                return ['code' => 400, 'msg' => '数据填写有误'];
//                break;
//            }
            $materInfo=Db::name('material_kucun_view')
                ->where('wId',$wids1[0])
                ->where('bar_code',$wid)
                ->find();
            if (!$materInfo) {
                return ['code' => 400, 'msg' => '数据填写有误'];
                break;
            }
          if ($m1>($materInfo['countNum']-$materInfo['sendNum'])){
              return ['code' => 400, 'msg' => '数量大于剩余数量'];
              break;
                    }
            $mxData[] = [
                'num' => $m1,
                'warehouse_id' => $wids1[0],
                'material_dossier_id' => $materInfo['mdId'],
                "create_time" => time(),
                'update_time' => time()
            ];
        }
        return ['code'=>200,'msg'=>'','data'=>['importData'=>$importData,'mxData'=>$mxData]];
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @autho:xiangzi
     * @auth:true
     * @Date:2024/9/20
     * 导出
     */
    public function exportData()
    {
        $where=session($this->sessionKey);
        $list = Db::name($this->table)->alias('i')
            ->join('purveyor p','p.id=i.punter_id','left')
            ->join('admin u','u.id=i.out_user','left')
            ->where($where)
            ->field('i.*,p.name as pName,u.name as username')
            ->order('i.id DESC')
            ->select()->each(function ($item){
                $item['status']=$item['status']==1?'草稿':'已确认';
                return $item;
            });
        $title = [
            'id' => 'ID',
            'orderNum' => '单据编号',
            'type' => '业务类型',
            'pName' => '送货单位',
            'username' => '出库人',
            'outTime' => '出库时间',
            'status' => '状态',
        ];
        $name =$this->title;
        exportXlsData($name,$title,$list);
        exit();
    }
}